const express = require("express");
const db = require("../db/config");
const bodyParser = require("body-parser");
//图形验证码
const svgCaptcha = require("svg-captcha");
const nodeMail = require("./nodemailer");
//调用express.Router()方法创建路由对象、
const login = express.Router();

// 解析 application/json
login.use(bodyParser.json());
// 解析 application/x-www-form-urlencoded
//固定写法：解析post参数的。 写在路由的前面
login.use(express.urlencoded({ extended: true }));
// 设置允许跨域访问该服务
login.all("*", function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "PUT, GET, POST, DELETE, OPTIONS");
  res.header("Access-Control-Allow-Headers", "X-Requested-With");
  res.header("Access-Control-Allow-Headers", "Content-Type");
  res.header("Access-Control-Allow-Headers", "Authorization");
  next();
});
// 生成token
var { expressjwt: jwtt } = require("express-jwt");
const jwt = require("jsonwebtoken");
const secretkey = "Zhang"; // 定义秘钥
// 配置token 将/login , /getrandom / 列为白名单不需要token也能请求
login.use(
  jwtt({ secret: secretkey, algorithms: ["HS256"] }).unless({
    path: [
      "/",
      "/login",
      "/authCode",
      "/Emails",
      "/resetpass",
      "/register",
      "/checkemail",
      "/fileUpload",
      "/refrshNickname",
      "/refrshAvatar",
      "/UserInfo",
      "/delAvatar"
    ],
  })
);
login.use((err, req, res, next) => {
  if (err.name === "UnauthorizedError") {
    res.status(401).send("invalid token 还未登录哦 ... ");
  }
});

// 登陆
login.post("/login", (req, res) => {
  let { username, password } = req.query;
  console.log("用户名：", username);
  console.log("密码:", password);
  // 调用封装的查询语句比对数据是否相同，如果数据相同回调的data就会返回一个非空数组
  db.query(
    `select * from userinfo where username = '${username}' and password = '${password}' `,
    (data) => {
      if (data.length > 0) {
        const token = jwt.sign(Object.assign({}, data[0]), secretkey, {
          expiresIn: 60 * 60 * 2,
        });
        res.send({
          code: 200,
          msg: "登录成功!",
          role: data[0].role,
          id:data[0].id,
          nickname:data[0].nickname,
          avatar:data[0].avatar,
          token: token,
          filename:data[0].fileName
        });
      } else {
        res.send("登录失败");
      }
    }
  );
});

// 注册
login.post("/register", (req, res) => {
  // 解构赋值
  // let { username, password } = req.query;
  let name = req.query.username;
  let pwd = req.query.password;
  role = "user";
  db.insert(
    "userinfo",
    { username: name, password: pwd.toString(), role: role },
    (data) => {
      if (data.affectedRows > 0) {
        res.send({ code: 200, msg: "注册成功" });
      } else {
        res.send({ code: 100, msg: "注册失败" });
      }
    }
  );
});

//图形验证码
login.get("/authCode", (req, res) => {
  // 下面这行代码是随机生成验证码图片和文本并返回给客户端
  const c = svgCaptcha.create({
    width: 150,
    height: 40,
    size: 4, // 验证码长度
    ignoreChars: "0o1i", // 验证码字符中排除 0o1i
    color: true, // 验证码是否有彩色
    noise: 3, //干扰线
    background: "#666", // 背景颜色
  });
  res.send(c);
});

// 邮箱验证 返回的密码需要 base64  加密 前端解密
let code;
login.post("/Emails", async (req, res) => {
  const email = req.query.email;
  code = String(Math.floor(Math.random() * 1000000)).padEnd(6, "0"); //生成6位随机验证码
  //发送邮件
  const mail = {
    from: `邮箱验证测试测试"<862779506@qq.com>`, // 发件人
    subject: "验证码", //邮箱主题
    to: email, //收件人，这里由post请求传递过来
    // 邮件内容，用html格式编写
    html: `
          <p>您好！</p>
          <p>您的验证码是：<strong style="color:orangered;">${code}</strong></p>
          <p>如果不是您本人操作，请无视此邮件</p>
      `,
  };
  await nodeMail.sendMail(mail, (err, info) => {
    if (!err) {
      res.json({ msg: "验证码发送成功", code });
    } else {
      console.log(err);
      res.json({ msg: "验证码发送失败，请稍后重试" });
    }
  });
});

// 重置账号秘密
// 注册
login.post("/resetpass", (req, res) => {
  const { username, password } = req.query;
  db.update(
    "userinfo",
    { password: password },
    { username: username },
    (data) => {
      if (data.affectedRows > 0) {
        res.send({ code: 200, msg: "修改成功" });
      } else {
        res.send({ code: 100, msg: "修改失败" });
      }
    }
  );
});

/** 更新 头像   */
login.post("/refrshAvatar", (req, res) => {
  const { Image, id, fileName } = req.query;
  db.update(
    "userinfo",
    { avatar: Image ,fileName:fileName},
    { id: id },
    (data) => {
      if (data.affectedRows > 0) {
        res.send({ code: 200, msg: "编辑成功" });
      } else {
        res.send({ code: 100, msg: "编辑失败" });
      }
    }
  );
});
/** 删除头像 */
login.post("/delAvatar", (req, res) => {
  const { id } = req.query;
  db.query(`UPDATE userinfo set avatar = null,fileName = null WHERE id = ${id}`,(data)=>{
    if (data) {
      res.send({ code: 200, msg: "Successful", data });
    } else {
      res.send({ code: 100, msg: "error" });
    }
  })
});

/** 更新 Nickname
   */
login.post("/refrshNickname", (req, res) => {
  const { nickname, id } = req.query;
  db.update(
    "userinfo",
    { nickname: nickname },
    { id: id },
    (data) => {
      if (data.affectedRows > 0) {
        res.send({ code: 200, msg: "编辑成功" });
      } else {
        res.send({ code: 100, msg: "编辑失败" });
      }
    }
  );
});

/** 获取用户信息 */
login.post('/UserInfo',(req,res)=>{
  const { id } = req.query
  db.query(`SELECT * FROM userinfo WHERE id = ${id}`,(data)=>{
    if (data.length > 0) {
      res.send({ code: 200, msg: "Successful", data });
    } else {
      res.send({ code: 100, msg: "error" });
    }
  })
})

// 检索邮箱是否已被注册过
login.post("/checkemail", (req, res) => {
  let email = req.query.email;
  db.query(`select * from userinfo where username = '${email}'`, (data) => {
    if (data.length > 0) {
      res.send({ code: 200, msg: "邮箱已存在,请勿重复注册" });
    } else {
      res.send({ code: 100, msg: "邮箱还未注册" });
    }
  });
});
// 使用module.exprots导出路由对象
module.exports = login;
